package com.pearlsoft.webapp.core.web.listener;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.ContextLoaderListener;

import com.pearlsoft.webapp.core.web.session.SessionProfile;
import com.pearlsoft.webapp.core.web.util.RightUtil;

/**
 * 
 * StartupListener
 * 
 * @Creator haitingr
 * @Create-DateTime 2011-10-27
 */
public class StartupListener extends ContextLoaderListener implements ServletContextListener{

	private static final Log logger = LogFactory.getLog(StartupListener.class);

	public void contextInitialized(ServletContextEvent event) {
	     ServletContext context = event.getServletContext();
		logger.debug("initializing spring context...");
		super.contextInitialized(event);
		logger.info("spring context setup successfully!!!");
		
		logger.info("start init system params");
		initParams(context);
		logger.info("end init system params");
		logger.info("start init user right");
		//initUserRight(context);
		logger.info("start init user right");
	}
	
	
	private void initParams(ServletContext context){
		ApplicationContext springContext = this.getCurrentWebApplicationContext();
		JdbcTemplate jdbcTemplate = springContext.getBean("jdbcTemplate", JdbcTemplate.class);
		String sql ="SELECT * FROM SYS_PARAM WHERE C_STATUS='1'";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		for (Iterator<Map<String, Object>> iter = list.iterator(); iter.hasNext();) {
			Map<String, Object> map = iter.next();
			String key= (String) map.get("PARAM_KEY");
			 context.setAttribute((String) key, (String) map.get("PARAM_VALUE"));
			 if(!System.getProperties().containsKey( key)){
					System.setProperty( key, (String) map.get("PARAM_VALUE"));
					logger.info("系统初始化["+(String) map.get("PARAM_NAME")+"]:"+(String) map.get("PARAM_VALUE"));
				}
			
			
		}
		if(!System.getProperties().containsKey( "APP_PATH")){
			System.setProperty( "APP_PATH",context.getRealPath("/"));
			logger.info("系统初始化[应用路径]:"+context.getRealPath("/"));
		}
		
	}

	public void initUserRight(ServletContext context){
		ApplicationContext springContext = this.getCurrentWebApplicationContext();
		JdbcTemplate jdbcTemplate = springContext.getBean("jdbcTemplate", JdbcTemplate.class);
		String sql ="SELECT * FROM SYS_USER ";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		for (Iterator<Map<String, Object>> iter = list.iterator(); iter.hasNext();) {
			Map<String, Object> map = iter.next();
			String userId= (String) map.get("USER_ID");
			String userCode = (String) map.get("USER_CODE");
			rightXml(jdbcTemplate, userId,userCode);
			
		}
	}
	
	public void rightXml(JdbcTemplate jdbcTemplate,String userId,String userCode){
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("MENUS");
		root.addAttribute("owner",userCode);
		if(!(SessionProfile.ADMIN_CODE).equals(userCode)){
			String sql = "SELECT * FROM (SELECT DISTINCT(C.MENU_ID) FROM (SELECT * FROM sys_user_role   WHERE USER_ID=?) B LEFT JOIN sys_role_menu C " +
					"ON B.ROLE_ID = C.ROLE_ID WHERE C.MENU_ID IS NOT NULL  ) D LEFT JOIN sys_menu F ON D.MENU_ID = F.MENU_ID WHERE F.C_STATUS='1' ORDER BY F.MENU_PARENT_ID,F.MENU_ORDER";
			List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[] {userId});
			RightUtil.buildUserRightXml(list, userCode);
		}else{
			String sql = "SELECT * FROM  sys_menu F  ORDER BY F.MENU_PARENT_ID,F.MENU_ORDER";
			List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
			RightUtil.buildUserRightXml(list, userCode);
		}
	}
}
